package com.yjzx.util.common.util.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author yjzx
 * @date 2024/6/20
 * @description JacksonUtil
 */
public class JacksonUtil {
    /*
      <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-databind</artifactId>
           <version>2.9.7</version>
      </dependency>
     */
    public final static ObjectMapper objectMapper = new ObjectMapper();
    static {

        //序列化只包含不为空字段，
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //反序列化忽略不存在字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    public static ObjectMapper getInstance() {
        return objectMapper;
    }
    /**
     * 将java对象转换为json，
     * //@JsonProperty 属性名重命名
     * //@JsonIgnore 忽略指定字段
     * //@JSONField 修改某个属性的输出名称,规定其支持序列化或者反序列化与否以及规定序列化顺序.
     * @param o
     * @return
     */
    public static String toStr(Object o) {
        String str = null;
        try {
            str = objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throwException(o.toString()+"对象出现"+e);
        }
        return str;
    }

    public static <T> T toObj(String jsonStr, TypeReference<T> tf) {
        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            throwException("json字符串"+jsonStr+"， 转对象异常："+e);
        } catch (IOException io) {
            throwException("json字符串"+jsonStr+"， IO异常："+io);
        }
        return t;
    }

    public static <T> T toObj(String jsonStr, Class<T> tf) {
        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            throwException("json字符串"+jsonStr+"， 转对象异常："+e);
        } catch (IOException io) {
            throwException("json字符串"+jsonStr+"， IO异常："+io);
        }
        return t;
    }

    public static Exception throwException(String message){
        throw new RuntimeException(message);
    }

}
